﻿using Business.ReadAPI.Application.Accounts;
using Business.ReadAPI.Application.Breeds;
using Business.ReadAPI.Application.FarmEnterprises;
using Business.ReadAPI.Application.Foods;
using Business.ReadAPI.Application.Images;
using Business.ReadAPI.Application.Immunities;
using Business.ReadAPI.Application.Machinings;
using Business.ReadAPI.Application.Products;
using Business.ReadAPI.Application.Slaughtes;
using Common.Domain;
using Common.Infrastructure.Repository;
using Common.Services;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.XSSF.UserModel;
using QiNiuStorage;

namespace Business.ReadAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ManagementController : ControllerBase
    {
        private readonly IMediator mediator;
        public ManagementController(IMediator mediator)
        {
            this.mediator = mediator;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="username">账号</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [HttpPost("Login")]
        public async Task<APIResult> Login(string username, string password)
        {
            LoginRequestModel requet = new LoginRequestModel();
            requet.AccountName = username;
            requet.AccountPwd = password;
            return await mediator.Send(requet);
        }
        /// <summary>
        /// 获取食品
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetFood")]
        public async Task<APIResult> GetFood()
        {
            FoodQueryRequestModel requet = new FoodQueryRequestModel();
            return await mediator.Send(requet);
        }
        /// <summary>
        /// 获取产品
        /// </summary>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">页码</param>
        /// <returns></returns>
        [HttpGet("GetProduct")]
        public async Task<APIResult> GetProduct(int PageIndex, int PageSize, int foodId)
        {
            ProductQueryRequestModel request = new ProductQueryRequestModel();
            request.PageIndex = PageIndex;
            request.PageSize = PageSize;
            request.FoodId = foodId;
            return await mediator.Send(request);
        }
        /// <summary>
        /// 根据主键反填全部信息
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        [HttpGet("FanProduct")]
        public async Task<APIResult> FanProduct(int productId)
        {
            ProjectReverseRequestModel request = new ProjectReverseRequestModel();
            request.ProductId = productId;
            return await mediator.Send(request);
        }
        /// <summary>
        /// 获取养殖信息
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        [HttpGet("GetBreed")]
        public async Task<APIResult> GetBreed()
        {
            BreedQueryRequestModel request = new BreedQueryRequestModel();
            return await mediator.Send(request);
        }
        /// <summary>
        /// 获取保健信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetImmunities")]
        public async Task<APIResult> GetImmunities()
        {
            ImmunitiesQueryRequestModel request = new ImmunitiesQueryRequestModel();
            return await mediator.Send(request);
        }
        
        /// <summary>
        /// 获取图片路径
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetImage")]
        public async Task<APIResult> GetImage(string? productCode)
        {
            ImageQueryRequestModel request = new ImageQueryRequestModel();
            request.ProductCode = productCode;
            return await mediator.Send(request);
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("UploadFile")]
        public IActionResult UploadFile(IFormFile file)
        {
            //string savepath = Directory.GetCurrentDirectory() + @"\wwwroot\img\";
            //string newFileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            //using (FileStream fs = new FileStream(savepath + newFileName, FileMode.Create))
            //{
            //    file.CopyTo(fs);
            //    fs.Flush();
            //}
            //var url = "/img/"+
            //return Ok(newFileName);
            var filename = file.FileName;
            filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetExtension(filename);
            var path = Directory.GetCurrentDirectory() + "\\wwwroot\\img\\" + filename;
            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                file.CopyTo(fs);
                fs.Flush();
            }
            var url = "/img/" + filename;

            string qiniuurl = QiNiuHelper.QiNiuUploadFile(filename);

            return Ok(url);
        }
        /// <summary>
        /// 删除文件夹图片
        /// </summary>
        /// <param name="imageName"></param>
        /// <returns></returns>
        [HttpPost("DeleteImages")]
        public string DeleteImages(string imageName)
        {
            imageName = imageName.Replace("https://localhost:44391/img/", "");
            var imagePath = Environment.CurrentDirectory + "\\wwwroot\\img\\" + imageName;

            // 删除图片
            System.IO.File.Delete(imagePath);
            return "图片删除成功";
        }
        /// <summary>
        /// 获取企业信息
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        [HttpGet("GetFarm")]
        public async Task<APIResult> GetFarm()
        {
            FarmQueryRequestModel request = new FarmQueryRequestModel();
            return await mediator.Send(request);
        }
        /// <summary>
        /// 获取屠宰信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetSlaughte")]
        public async Task<APIResult> GetSlaughte()
        {
            SlaughteQueryRequestModel request = new SlaughteQueryRequestModel();
            return await mediator.Send(request);
        }
        /// <summary>
        /// 获取屠宰企业信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetSlaughteQ")]
        public async Task<APIResult> GetSlaughteQ()
        {
            SlaughteQQueryRequestModel request = new SlaughteQQueryRequestModel();
            return await mediator.Send(request);
        }
        /// <summary>
        /// 获取深加工信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetMachining")]
        public async Task<APIResult> GetMachining()
        {
            MachiningQueryRequestModel request = new MachiningQueryRequestModel();
            return await mediator.Send(request);
        }
        /// <summary>
        /// 获取原料信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetMaterial")]
        public async Task<APIResult> GetMaterial()
        {
            MaterialQueryRequestModel request = new MaterialQueryRequestModel();
            return await mediator.Send(request);
        }
        /// <summary>
        /// 获取辅料信息信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAccessories")]
        public async Task<APIResult> GetAccessories()
        {
            AccessoriesQueryRequestModel request = new AccessoriesQueryRequestModel();
            return await mediator.Send(request);
        }
        /// <summary>
        /// 获取添加剂信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAdditive")]
        public async Task<APIResult> GetAdditive()
        {
            AdditiveQueryRequestModel request = new AdditiveQueryRequestModel();
            return await mediator.Send(request);
        }
        /// <summary>
        /// 获取包材信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetPack")]
        public async Task<APIResult> GetPack()
        {
            PackQueryRequestModel request = new PackQueryRequestModel();
            return await mediator.Send(request);
        }
        /// <summary>
        /// 获取加工企业信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetMachiningJ")]
        public async Task<APIResult> GetMachiningJ()
        {
            MachiningJQueryRequestModel request = new MachiningJQueryRequestModel();
            return await mediator.Send(request);
        }
        /// <summary>
        /// 获取时间
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetDate")]
        public IActionResult GetDate()
        {
            var result = DateTime.Now.ToString("yyyyMMhhss");
            return Ok(result);
        }
        /// <summary>
        /// NPOI导出商品信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("ExportExcel")]
        public async Task<APIResult> ExportExcel(int pageSize)
        {
            try
            {
                ProductQueryRequestModel model = new ProductQueryRequestModel();
                model.PageSize = pageSize;
                model.PageIndex = 1;
                var result = await mediator.Send(model);
                var product = new List<ProductQueryResponseModel>();
                //if(result.Data!=null)
                //{
                //    var list = (APIPagging<Product>)result.Data;
                //}
                var wb = new XSSFWorkbook();
                var sheet = wb.CreateSheet("产品信息");
                var sheet_row = sheet.CreateRow(0);
                sheet_row.CreateCell(0).SetCellValue("商品编号");
                sheet_row.CreateCell(1).SetCellValue("生产批次");
                sheet_row.CreateCell(2).SetCellValue("保质期");
                sheet_row.CreateCell(3).SetCellValue("生产许可证");
                sheet_row.CreateCell(4).SetCellValue("生产企业");

                var index = 1;
                foreach (var item in product)
                {
                    var row = sheet.CreateRow(index);
                    row.CreateCell(0).SetCellValue(item.ProductCode);
                    row.CreateCell(1).SetCellValue(item.ProductionBatch);
                    row.CreateCell(2).SetCellValue(item.ShelfLife);
                    row.CreateCell(3).SetCellValue(item.LicenseNumber);
                    row.CreateCell(4).SetCellValue(item.Enterprise);
                    index++;
                }

                byte[] buffer;
                using (var ms = new MemoryStream())
                {
                    wb.Write(ms);
                    buffer = ms.ToArray();
                }

                var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
                var filepath = Path.Combine("wwwroot/excel/" + filename);
                using (var fs = new FileStream(filepath, FileMode.Create))
                {
                    fs.Write(buffer, 0, buffer.Length);
                }
                result.Data = filename;
                return result;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
